﻿using System;
using System.IO;

public static class FileHelper
{
    public delegate void FileOperate(string filePath);

    public static void ForEveryFile(string rootPath, FileOperate fileOperate)
    {
        try //个别文件夹 可能会因为权限问题导致无法访问
        {
            //输出当前文件夹下的所有文件路径
            string[] files = Directory.GetFiles(rootPath);
            for (int i = 0; i < files.Length; i++)
            {
                //  Console.WriteLine(files[i]); //对文件执行的操作
                fileOperate(files[i]);
            }

            //对所有的子文件夹执行相同的操作
            string[] subDirs = Directory.GetDirectories(rootPath);//拿到所有的子文件夹
            for (int i = 0; i < subDirs.Length; i++)
            {
                ForEveryFile(subDirs[i], fileOperate);
            }
        }
        catch (Exception)
        {
            Console.WriteLine("无法访问:" + rootPath);
        }
    }

    public static void CopyFile(string pathSource, string pathWrite)
    {
        //using (FileStream fsRead = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read),
        //    fsWrite = new FileStream(writePath,FileMode.Create,FileAccess.Write,FileShare.None))
        using (FileStream fsRead = File.OpenRead(pathSource), fsWrite = File.Create(pathWrite))
        {
            byte[] arr = new byte[1024 * 1024];//1MB缓冲区

            while (true)
            {
                //读取数据放到缓冲区
                int lenght = fsRead.Read(arr, 0, arr.Length); //返回的length是真实读取到的字节数量
                                                              //从缓冲区写入到新文件
                fsWrite.Write(arr, 0, lenght);

                //   Console.WriteLine($"已经复制:{fsRead.Position}字节,{fsRead.Position / (float)fsRead.Length:p}");
                if (fsRead.Position == fsRead.Length)//判断读取流是否读取到文件末尾
                {
                    fsWrite.Flush();//让操作系统缓冲区的数据全部写入硬盘
                    break;
                }
            }
            Console.WriteLine("复制完成");
        }
    }

    public static void CreatDirectoryIfNotExist(string path)
    {
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
    }
}